package com.linkstec.cdc;

import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

public class SqlServerTest {
	protected final static Logger logger = LoggerFactory.getLogger(SqlServerTest.class);
    public static void main(String[] args) {
        Connection conn;
        Statement stmt;
        ResultSet rs;
        String url = "jdbc:sqlserver://192.168.2.144:1433;DatabaseName=Demo;";
        String sql = "select * from cdc.dbo_tab_CT";
        try {
            // 连接数据库
            conn = DriverManager.getConnection(url, "sa", "smot@12345");
            // 建立Statement对象
            stmt = conn.createStatement();
            /**
             * Statement createStatement() 创建一个 Statement 对象来将 SQL 语句发送到数据库。
             */
            // 执行数据库查询语句
            rs = stmt.executeQuery(sql);
            /**
             * ResultSet executeQuery(String sql) throws SQLException 执行给定的 SQL
             * 语句，该语句返回单个 ResultSet 对象
             */
            while (rs.next()) {
                int id = rs.getInt("id");
                Date birthDate = rs.getDate("birthDate");
                String name = rs.getString("name");
                logger.info("id:" + id + "\tbirthDate:" + birthDate + "\tname:" + name);
                
                Map<String, Object> dataMap=new HashMap<String, Object>();
                ResultSetMetaData rsMeta=rs.getMetaData();
                int columnCount=rsMeta.getColumnCount();
                for (int i=1; i<=columnCount; i++) {
                    dataMap.put(rsMeta.getColumnLabel(i), rs.getObject(i));
                }
                logger.info(dataMap + "");
            }
            if (rs != null) {
                rs.close();
                rs = null;
            }
            if (stmt != null) {
                stmt.close();
                stmt = null;
            }
            if (conn != null) {
                conn.close();
                conn = null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("数据库连接失败");
        }
    }
}
